import { createRouter, createWebHistory } from "vue-router";

import Layout from "@/pages/sys/Layout.vue";

export const constRoutes = [
    {
        path: "/redirect",
        component: Layout,
        meta: { hidden: true },
        children: [
          {
            path: "/redirect/:path(.*)",
            component: () => import("@/pages/sys/redirect.vue"),
          },
        ]
    },    
    {
        path: "/login",
        component: () => import("@/pages/sys/Login.vue"),
    },
    {
        path: "/",
        component: Layout,
        redirect: "/dashboard",
        children: [
            {
                path: "dashboard",
                component: () => import("@/pages/sys/dashboard.vue"),
            },
            {
                path: "401",
                component: () => import("@/pages/error-page/401.vue"),
                meta: { hidden: true },
            },
            {
                path: "404",
                component: () => import("@/pages/error-page/404.vue"),
                meta: { hidden: true },
            }
        ],
    },
];

const router = createRouter({
    routes: constRoutes,
    history: createWebHistory(),
});

// 白名单路由
const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
  const hasToken = localStorage.getItem("token");
  if (hasToken) {
    if (to.path === "/login"){
      // 如果已登录，跳转首页
      next({ path: "/" });
    } else {
      if (to.matched.length === 0) {
        from.name ? next({ name: from.name }) : next("/404");
      } else {
        // 如果路由参数中有 title，覆盖路由元信息中的 title
        const title = (to.params.title) || (to.query.title);
        if (title) {
          to.meta.title = title;
        }
        next();
      }
    }
  } else {
    // 未登录
    if (whiteList.indexOf(to.path) !== -1) {
      // 在白名单，直接进入
      next();
    } else {
      // 不在白名单，重定向到登录页
      const params = new URLSearchParams(to.query);
      const queryString = params.toString();
      const redirect = queryString ? `${to.path}?${queryString}` : to.path;
      next(`/login?redirect=${encodeURIComponent(redirect)}`);
    }
  }
});

export default router;
